<template>
  <piece>
    <piece-item
      @click="callOutDeliveryTimeOp"
      left-icon="icon-songdashijian1"
      :left-icon-custom="true"
      :content-left="isImmediate ? '尽快制作' : '指定时间'"
      :content-right="arrivalFormatTime"
    />
  </piece>
  <predetermine-datetime-selector
    @timeCallback="timeCallback"
    :content="generatedPredetermineDatesAndTimeRangesInfo?.datesTimes"
    title="选择预送达时间"
    ref="selfPickupTimeOpRef"
  />
</template>

<script setup lang="ts">
import { inject, watch, computed, ref, type Ref, onMounted } from 'vue'
import Piece from '@/components/piece/index.vue'
import PieceItem from '@/components/piece/piece-item/index.vue'
import PredetermineDatetimeSelector from '@/components/predetermine-datetime-selector/index.vue'
import {
  GeneratePredetermineDatesAndTimeRangesNeedInfo,
  PredetermineDateAndTime
} from '@/components/predetermine-datetime-selector/utils.type'
import { PredetermineDatesAndTimeRangesGenerator } from '@/components/predetermine-datetime-selector/utils'
import { TimeOperations } from '@/utils/TimeUtils'
const props = defineProps<{ shopPredetermineInfo: GeneratePredetermineDatesAndTimeRangesNeedInfo | undefined }>()
// 调起送达时间选择组件
const selfPickupTimeOpRef = ref()
function callOutDeliveryTimeOp() {
  selfPickupTimeOpRef.value.callOut()
}
// 可选择的预约信息列表（dates and times）
const generatedPredetermineDatesAndTimeRangesInfo = computed(() => {
  if (props.shopPredetermineInfo == null) return undefined
  return PredetermineDatesAndTimeRangesGenerator.gen(props.shopPredetermineInfo)
})

// 动态计算送达显示的时间与是否"尽快送达"
const isImmediate = ref<boolean>(true)
let choosePredetermineDateAndTime = ref(new PredetermineDateAndTime())
// 到达时间format格式
const arrivalFormatTime = computed(() => {
  if (choosePredetermineDateAndTime.value == null || generatedPredetermineDatesAndTimeRangesInfo.value == null)
    return ''
  if (isImmediate.value) {
    return `预计 ${PredetermineDateAndTime.format(
      generatedPredetermineDatesAndTimeRangesInfo.value!.immediatePredetermineTime
    )} 送达`
  } else {
    return `${PredetermineDateAndTime.format(choosePredetermineDateAndTime.value)}`
  }
})
// 选择时间
function timeCallback(predetermineDateAndTime: PredetermineDateAndTime) {
  // 这里能获取那肯定predetermineDateAndTime是有值的，从而推出generatedPredetermineDatesAndTimeRangesInfo肯定是有值的
  isImmediate.value = generatedPredetermineDatesAndTimeRangesInfo.value!.isImmediateDateAndTime(predetermineDateAndTime)
  if (!isImmediate.value) choosePredetermineDateAndTime.value = predetermineDateAndTime
}
// 动态计算指定时间
const specifiedTime = computed(() => {
  if (isImmediate.value) return null
  return new TimeOperations()
    .update(choosePredetermineDateAndTime.value.dateItem?.ymdFormat, choosePredetermineDateAndTime.value.timeItem?.time)
    .getCoreDate()
})
defineExpose({
  isImmediate,
  specifiedTime
})
</script>

<style scoped></style>
